<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, onBeforeUnmount } from 'vue';
import { initializeTranslationGroups, triggerTranslation, addTranslationGroup } from '../utils/translationService';
import { useRoute } from 'vue-router';
import { generateImages as apiGenerateImages, TaskType } from '../utils/ApiMethod';
import type { GenerateImageParams } from '../utils/ApiMethod';
import { initKeywordTranslator, rescanKeywords, triggerKeywordTranslation } from '../utils/KeywordTranslator'; // 导入关键词翻译器
import axiosInstance from '../utils/axios';
// import { useThemeStore } from '@/stores';

// 获取路由对象
const route = useRoute();

// 描述词相关状态
const promptText = ref('');
const keywords = reactive<Record<string, { color: string, value: string, index: number, count: number }>>({});
const keywordColors = ref<string[]>([]);
const keywordCount = ref(0); // 用于生成关键词序号
const lastSelection = ref<{ start: number, end: number, containerEl: HTMLElement } | null>(null); // 保存最后一次的选区

// 生成的图片相关状态
const isGenerating = ref(false);
const generatedImages = ref<{ url: string, prompt: string }[]>([]);
const sliderValue = ref(50);
const isAI = ref(false);
const switchNum = ref(false);
const PicsliderValue = ref(50);
const switchNumsliderValue = ref(4);

// 添加新的状态数据
const taskCategoryDict: Record<string, string> = {
  "蜡烛": "M",
  "动物": "A",
  "植物": "P",
  "人物": "H",
  "风景": "L"
};

const processPerson = ["张三", "王四", "李五", "赵六"];

// 添加图片尺寸选项
const imgSizeOptions = ["1:1", "1:2", "2:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16"];

// 添加选择状态
const selectedCategory = ref(Object.keys(taskCategoryDict)[0]);
const selectedPerson = ref(processPerson[0]);
const imgSize = ref("3:2"); // 默认图片比例

// 为不同的taskType设置不同的imgSize默认值
watch(() => isAI.value, (newVal) => {
  imgSize.value = newVal ? "1:2" : "3:2";
});

// 处理slider输入，确保值为4的倍数
const handleSwitchNumInput = (e: Event) => {
  const value = parseInt((e.target as HTMLInputElement).value);
  if (!isNaN(value)) {
    // 确保值为4的倍数
    switchNumsliderValue.value = Math.floor(value / 4) * 4;
    // 确保至少为4
    if (switchNumsliderValue.value < 4) {
      switchNumsliderValue.value = 4;
    }
  }
};

const handleSliderInput = (e: Event) => {
  const value = parseInt((e.target as HTMLInputElement).value);
  if (!isNaN(value)) {
    sliderValue.value = value;
  }
};

// 随机颜色生成函数
function getRandomColor() {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFBE0B', 
    '#FB5607', '#8338EC', '#3A86FF', '#FF006E',
    '#A5BE00', '#5F0F40', '#9B5DE5', '#00BBF9'
  ];
  
  // 过滤掉已经使用的颜色
  const availableColors = colors.filter(color => !keywordColors.value.includes(color));
  
  // 如果所有颜色都已使用，则重新使用所有颜色
  if (availableColors.length === 0) {
    return colors[Math.floor(Math.random() * colors.length)];
  }
  
  return availableColors[Math.floor(Math.random() * availableColors.length)];
}

// 处理描述词输入
function handlePromptInput(event: Event) {
  const editableDiv = event.target as HTMLElement;
  const content = editableDiv.innerHTML;
  
  // 保存文本
  promptText.value = content;
  
  // 保存当前选区
  lastSelection.value = saveSelection(editableDiv);
  
  // 只有当内容为空时，才清除所有关键词和计数器
  if (content.trim() === '') {
    Object.keys(keywords).forEach(colorId => {
      delete keywords[colorId];
    });
    keywordColors.value = [];
    keywordCount.value = 0;
  }
  
  // 检查关键词标签状态
  checkKeywordTags();
  
  // 翻译服务会自动处理从英文到中文的翻译
}

// 处理预览框输入
function handlePreviewInput(event: Event) {
  // 预览框内容变化时的处理逻辑
  // 翻译服务会自动处理从中文到英文的翻译
  const previewDiv = event.target as HTMLElement;
  const content = previewDiv.innerText || previewDiv.textContent || '';
  
  console.log('Preview content changed:', content);
}

// 获取格式化后的描述词文本（用于显示）
const formattedPrompt = computed(() => {
  // 返回带有颜色标记的描述词文本
  return promptText.value;
});

// 获取最终提交的描述词文本
const finalPrompt = computed(() => {
  let result = promptText.value;

  // 创建临时DOM元素来处理HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = result;
  
  // 处理关键词标签
  const tags = tempDiv.querySelectorAll('.keyword-tag');
  tags.forEach(tag => {
    // 获取标签文本内容（已经是{k?}格式）
    const tagText = tag.textContent || '';
    // 用纯文本替换标签元素
    const textNode = document.createTextNode(tagText);
    tag.parentNode?.replaceChild(textNode, tag);
  });
  
  // 获取处理后的纯文本
  result = tempDiv.textContent || '';
  
  return result;
});

// 生成图片函数
function generateImages() {
  if (isGenerating.value) return;
  
  // 获取最终的提示词
  const prompt = finalPrompt.value;
  if (!prompt.trim()) {
    // 如果提示词为空，给出提示
    alert('请输入描述词');
    return;
  }
  
  // 状态更新
  isGenerating.value = true;
  generatedImages.value = [];
  
  // 准备API参数
  const params: GenerateImageParams = {
    type: isAI.value ? TaskType.AI : TaskType.NORMAL,
    prompt,
    strength: sliderValue.value,
    keywords: Object.keys(keywords).length > 0 ? formatKeywordsForApi() : undefined
  };
  
  // 调用API
  apiGenerateImages(params)
    .then(response => {
      console.log('API生成图片成功:', response);
      // 处理响应数据
      if (response.success && response.images && response.images.length > 0) {
        generatedImages.value = response.images;
      } else {
        console.error('API返回数据格式不符合预期');
        alert('生成图片失败，请稍后重试');
      }
    })
    .catch(error => {
      console.error('API生成图片失败:', error);
      alert('生成图片失败，请稍后重试');
    })
    .finally(() => {
      isGenerating.value = false;
    });
}

// 格式化关键词为API需要的格式
function formatKeywordsForApi() {
    const formattedKeywords: Record<string, string> = {};
    
    // 遍历关键词对象
    Object.entries(keywords).forEach(([colorId, keyword]) => {
      // 使用k+index作为键名
      const keyName = `k${keyword.index}`;
      // 使用^分隔关键词值
      const keyValues = keyword.value.split(',').map(item => item.trim()).join('^');
      formattedKeywords[keyName] = keyValues;
    });
    
  return formattedKeywords;
}

// 选择生成的图片
function selectImage(image: { url: string, prompt: string }) {
  // 实现图片选择功能
  console.log('选择图片:', image);
  
  // 将选中图片的提示词替换到描述词输入框
  const promptInput = document.querySelector('.prompt-input') as HTMLElement;
  if (promptInput) {
    promptInput.innerHTML = image.prompt;
    promptText.value = image.prompt;
    
    // 触发描述词输入事件，更新关键词状态
    handlePromptInput({ target: promptInput } as unknown as Event);
  }
  
  // 滚动到页面顶部，方便用户查看和编辑
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

// 辅助函数，确保CSS选择器中的特殊字符被正确转义
function escapeCssSelector(selector: string): string {
  // 转义选择器中的特殊字符: !"#$%&'()*+,-./:;<=>?@[\]^`{|}~
  // 这里我们主要关注的是颜色值中的#符号
  return selector.replace(/([!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~])/g, '\\$1');
}

// 修改 handleKeywordInput 函数，使用独立的关键词翻译器
function handleKeywordInput(event: Event, colorId: string) {
  const input = event.target as HTMLInputElement;
  const value = input.value;
  
  // 更新关键词值
  if (keywords[colorId]) {
    keywords[colorId].value = value;
    
    try {
      // 获取关键词的真实索引
      const keywordIndex = keywords[colorId].index;
      console.log(`关键词输入变化: colorId=${colorId}, keywordIndex=${keywordIndex}, 文本=${value}`);
      
      // 使用keywordIndex直接触发翻译
    setTimeout(() => {
        triggerKeywordTranslation(keywordIndex, false);
    }, 2000);
    } catch (error) {
      console.error('处理关键词输入时出错:', error);
    }
  }
}

// 修改 createKeywordTranslationGroup 函数，使用关键词实际index而不是数组位置作为翻译组索引
function createKeywordTranslationGroup(colorId: string, arrayIndex: number) {
  // 获取关键词的实际索引，从keywords对象中读取
  const keywordIndex = keywords[colorId]?.index || arrayIndex + 1;
  
  console.log(`尝试创建关键词翻译组: colorId=${colorId}, 数组位置=${arrayIndex}, 关键词索引=${keywordIndex}`);
  
  // 安全处理colorId，确保可以作为CSS选择器使用
  const safeColorId = escapeCssSelector(colorId);
  
  // 首先检查元素是否存在
  const sourceSelector = `.keyword-input[data-keyword-id="${safeColorId}"]`;
  const targetSelector = `.keyword-translation[data-keyword-id="${safeColorId}"]`;
  
  const sourceElement = document.querySelector(sourceSelector);
  const targetElement = document.querySelector(targetSelector);
  
  console.log(`检查元素: sourceSelector=${sourceSelector}, 元素${sourceElement ? '存在' : '不存在'}`);
  console.log(`检查元素: targetSelector=${targetSelector}, 元素${targetElement ? '存在' : '不存在'}`);
  
  if (!sourceElement || !targetElement) {
    console.warn(`未找到关键词翻译元素，将在稍后重试: colorId=${colorId}`);
    
    // 如果元素不存在，延迟再次尝试
    setTimeout(() => {
      const retrySource = document.querySelector(sourceSelector);
      const retryTarget = document.querySelector(targetSelector);
      
      console.log(`重试检查元素: sourceSelector=${sourceSelector}, 元素${retrySource ? '存在' : '不存在'}`);
      console.log(`重试检查元素: targetSelector=${targetSelector}, 元素${retryTarget ? '存在' : '不存在'}`);
      
      if (retrySource && retryTarget) {
        console.log(`重试成功，现在创建关键词翻译组: colorId=${colorId}, 索引=${keywordIndex}`);
        
        // 直接使用DOM元素的选择器路径，确保能够匹配到正确的元素
        const exactSourceSelector = getExactSelector(retrySource);
        const exactTargetSelector = getExactSelector(retryTarget);
        
        console.log(`使用精确选择器: sourceSelector=${exactSourceSelector}`);
        console.log(`使用精确选择器: targetSelector=${exactTargetSelector}`);
        
        addTranslationGroup({
          sourceField: 'english',
          targetField: 'chinese',
          sourceSelector: exactSourceSelector || sourceSelector,
          targetSelector: exactTargetSelector || targetSelector,
          index: keywordIndex, // 使用关键词的真实索引作为翻译组索引
          twoWay: false // 关键词翻译是单向的
        });
        
        // 标记该元素已有翻译组
        retrySource.setAttribute('data-translation-group', 'true');
      } else {
        console.error(`重试失败，无法找到关键词翻译元素: sourceSelector=${sourceSelector}, targetSelector=${targetSelector}`);
      }
    }, 500);
    return;
  }
  
  // 获取精确的选择器路径
  const exactSourceSelector = getExactSelector(sourceElement);
  const exactTargetSelector = getExactSelector(targetElement);
  
  console.log(`使用精确选择器: sourceSelector=${exactSourceSelector}`);
  console.log(`使用精确选择器: targetSelector=${exactTargetSelector}`);
  
  // 添加一个新的翻译组，为每个关键词输入框和对应的翻译框建立映射
  addTranslationGroup({
    sourceField: 'english',
    targetField: 'chinese',
    sourceSelector: exactSourceSelector || sourceSelector,
    targetSelector: exactTargetSelector || targetSelector,
    index: keywordIndex, // 使用关键词的真实索引作为翻译组索引
    twoWay: false // 关键词翻译是单向的
  });
  
  // 标记该元素已有翻译组
  sourceElement.setAttribute('data-translation-group', 'true');
}

// 获取元素的精确选择器路径
function getExactSelector(element: Element): string {
  if (!element) return '';
  
  // 尝试使用更简单直接的选择器
  if (element.id) {
    return `#${element.id}`;
  }
  
  // 获取data-keyword-id属性值
  const keywordId = element.getAttribute('data-keyword-id');
  if (keywordId) {
    const elementTag = element.tagName.toLowerCase();
    // 使用类名和属性选择器组合
    return `${elementTag}[data-keyword-id="${escapeCssSelector(keywordId)}"]`;
  }
  
  // 如果没有明确的标识符，则构建完整路径（但通常不会走到这步）
  return '';
}

// 监听关键词变化，自动创建和移除翻译组
watch(() => Object.keys(keywords).length, (newCount, oldCount) => {
  console.log(`关键词数量变化: ${oldCount} -> ${newCount}`);
  // 当添加新关键词时，创建翻译组
  if (newCount > oldCount) {
    // 为新添加的每个关键词创建翻译组
    Object.entries(keywords).forEach(([colorId, keyword], index) => {
      // 检查该关键词是否已有翻译组
      const inputElement = document.querySelector(`.keyword-input[data-keyword-id="${colorId}"]`);
      if (inputElement && !inputElement.hasAttribute('data-translation-group')) {
        createKeywordTranslationGroup(colorId, index);
        // 标记该关键词已有翻译组
        inputElement.setAttribute('data-translation-group', 'true');
      }
    });
  }
});

// 修改添加关键词标签的函数
function addKeywordTag() {
  console.log('添加新关键词标签');
  // 原有逻辑保持不变
  const color = getRandomColor();
  
  let nextIndex = 1;
  const usedIndices = Object.values(keywords).map(k => k.index).sort((a, b) => a - b);
  
  for (let i = 0; i < usedIndices.length; i++) {
    if (usedIndices[i] !== nextIndex) {
      break;
    }
    nextIndex++;
  }
  
  keywordColors.value.push(color);
  
  keywords[color] = {
    color,
    value: '',
    index: nextIndex,
    count: 0
  };
  
  addKeywordToPrompt(color);
  
  // 使用延迟时间，确保DOM已完全更新后再触发扫描
  setTimeout(() => {
    console.log(`为新关键词重新扫描: 索引=${nextIndex}, 颜色=${color}`);
    rescanKeywords();
  }, 300);
}

// 修改 deleteKeyword 函数，在删除标签时更新扫描
function deleteKeyword(colorId: string) {
  if (!keywords[colorId]) return;
  
  // 获取被删除的关键词索引，用于日志
  const deletedIndex = keywords[colorId].index;
  console.log(`删除关键词: 索引=${deletedIndex}, 颜色=${colorId}`);
  
  // 原有逻辑保持不变
  const promptInput = document.querySelector('.prompt-input') as HTMLElement;
    if (promptInput) {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = promptText.value;
    
    const tags = tempDiv.querySelectorAll(`span.keyword-tag[data-keyword-id="${colorId}"]`);
    tags.forEach(tag => {
      tag.remove();
    });
    
    promptText.value = tempDiv.innerHTML;
    promptInput.innerHTML = tempDiv.innerHTML;
  }
  
  const colorIndex = keywordColors.value.indexOf(colorId);
  if (colorIndex !== -1) {
    keywordColors.value.splice(colorIndex, 1);
  }
  
  delete keywords[colorId];
  
  // 删除后更新关键词扫描，确保翻译组同步
      setTimeout(() => {
    console.log(`删除关键词后重新扫描: 索引=${deletedIndex}`);
    rescanKeywords();
  }, 300);
}

// 修改onMounted钩子，确保关键词翻译器初始化
onMounted(() => {
  // 初始化翻译组，自动绑定prompt-input和prompt-preview之间的翻译关系
  setTimeout(() => {
    // 先初始化主翻译组（描述词区域）
    initializeTranslationGroups();
    console.log('主翻译组初始化完成');
    
    // 初始化关键词翻译器
    console.log('在组件中初始化关键词翻译器');
    rescanKeywords();
    
    // 异步函数，用于检查和等待DOM元素
    const waitForElementsAndInitialize = async () => {
      try {
        // 检查关键词输入框是否已渲染
        const keywordElements = document.querySelectorAll('.keyword-input');
        console.log(`找到${keywordElements.length}个关键词输入框，要处理的关键词有${Object.keys(keywords).length}个`);
        
        // 不再需要单独创建翻译组，由KeywordTranslator处理
        
      } catch (error) {
        console.error('初始化翻译组时出错:', error);
      }
    };
    
    waitForElementsAndInitialize();
    
    // 处理URL参数
    if (route.query.prompt) {
      const promptInput = document.querySelector('.prompt-input') as HTMLElement;
      if (promptInput) {
        promptInput.innerHTML = route.query.prompt as string;
        promptText.value = promptInput.innerHTML;
        
        // 触发描述词输入事件，更新关键词状态
        handlePromptInput({ target: promptInput } as unknown as Event);
        
        // 手动触发第一次翻译
        setTimeout(() => {
          console.log('手动触发URL参数prompt的第一次翻译');
          triggerTranslation(0, false, 0);
        }, 800);
      }
    }
    
    if (route.query.image) {
      try {
        const imageUrl = decodeURIComponent(route.query.image as string);
        // 这个功能已经被移除，不再处理图片URL
        console.log('图片URL功能已移除:', imageUrl);
      } catch (error) {
        console.error('解码图片URL失败:', error);
      }
    }
  }, 500);
});

// 组件卸载时清理资源
onBeforeUnmount(() => {
  console.log('组件即将卸载，清理资源');
});

// 保存当前选区的方法
function saveCurrentSelection(element: HTMLElement) {
  lastSelection.value = saveSelection(element);
}

// 检查描述词中的关键词标签
function checkKeywordTags() {
  const promptInput = document.querySelector('.prompt-input') as HTMLElement;
  if (!promptInput) return;
  
  // 重置所有关键词计数
  Object.keys(keywords).forEach(colorId => {
    keywords[colorId].count = 0;
  });
  
  // 使用DOM操作计算每个关键词标签的出现次数
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = promptText.value;
  
  // 遍历所有关键词
  Object.keys(keywords).forEach(colorId => {
    // 查找所有匹配的标签
    const tags = tempDiv.querySelectorAll(`span.keyword-tag[data-keyword-id="${colorId}"]`);
    keywords[colorId].count = tags.length;
    
    // 如果计数为0，删除该关键词
    if (keywords[colorId].count === 0) {
      const colorIndex = keywordColors.value.indexOf(colorId);
      if (colorIndex !== -1) {
        keywordColors.value.splice(colorIndex, 1);
      }
      delete keywords[colorId];
    }
  });
}

// 在光标位置添加关键词标签
function addKeywordToPrompt(colorId: string) {
  const promptInput = document.querySelector('.prompt-input') as HTMLElement;
  
  // 确保输入框存在
  if (!promptInput) {
    return;
  }
  
  // 保存当前选择状态
  const savedSelection = saveSelection(promptInput);
  
  // 确保焦点在输入框内
  promptInput.focus();
  
  // 恢复之前的选择状态
  if (savedSelection) {
    restoreSelection(savedSelection);
  } else {
    // 如果没有选择范围，创建一个新的范围并将其设置到编辑区域的末尾
    const selection = window.getSelection();
    const range = document.createRange();
    // 确保编辑区域有内容节点
    if (promptInput.childNodes.length > 0) {
      const lastChild = promptInput.childNodes[promptInput.childNodes.length - 1];
      range.setEndAfter(lastChild);
    } else {
      // 如果编辑区域为空，将范围设置在编辑区域内
      range.selectNodeContents(promptInput);
    }
    // 创建新的选择并应用范围
    selection?.removeAllRanges();
    selection?.addRange(range);
  }
  
  // 创建关键词标签元素
  const tagText = `{k${keywords[colorId].index}}`;
  const tagHtml = `<span class="keyword-tag" style="background-color: ${colorId};" data-keyword-id="${colorId}" contenteditable="false">${tagText}</span>\u200B`; // 添加零宽空格
  
  // 插入标签
  document.execCommand('insertHTML', false, tagHtml);
  
  // 更新计数
  keywords[colorId].count++;
  
  // 保存更新后的内容
  promptText.value = promptInput.innerHTML;
  
  // 保持焦点在输入框内
  promptInput.focus();
}

// 保存选择状态的辅助函数
function saveSelection(containerEl: HTMLElement) {
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0) {
    const range = selection.getRangeAt(0);
    const preSelectionRange = range.cloneRange();
    preSelectionRange.selectNodeContents(containerEl);
    preSelectionRange.setEnd(range.startContainer, range.startOffset);
    const start = preSelectionRange.toString().length;
    
    return {
      start: start,
      end: start + range.toString().length,
      containerEl
    };
  }
  return null;
}

// 恢复选择状态的辅助函数
function restoreSelection(savedSel: { start: number, end: number, containerEl: HTMLElement }) {
  const selection = window.getSelection();
  const range = document.createRange();
  range.setStart(savedSel.containerEl, 0);
  range.collapse(true);
  
  const nodeStack: Node[] = [savedSel.containerEl];
  let node: Node | null = null;
  let foundStart = false;
  let stop = false;
  let charCount = 0;
  
  while (!stop && nodeStack.length > 0) {
    node = nodeStack.pop() || null;
    if (node && node.nodeType === 3) {
      const nextCharCount = charCount + (node.textContent?.length || 0);
      if (!foundStart && savedSel.start >= charCount && savedSel.start <= nextCharCount) {
        range.setStart(node, savedSel.start - charCount);
        foundStart = true;
      }
      if (foundStart && savedSel.end >= charCount && savedSel.end <= nextCharCount) {
        range.setEnd(node, savedSel.end - charCount);
        stop = true;
      }
      charCount = nextCharCount;
    } else if (node) {
      let i = node.childNodes.length;
      while (i--) {
        nodeStack.push(node.childNodes[i]);
      }
    }
  }
  
  if (selection) {
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

// 添加之前删除的addKeywordWithColor函数
function addKeywordWithColor(colorId: string) {
  // 如果颜色已存在，直接添加到光标位置
  if (keywords[colorId]) {
    // 获取正确的输入框元素
  const promptInput = document.querySelector('.prompt-input') as HTMLElement;
  if (promptInput) {
      // 保存当前选择状态（如果有的话）
      const savedSelection = lastSelection.value || saveSelection(promptInput);
      
      // 设置焦点到输入框
      promptInput.focus();
      
      // 短暂延迟以确保焦点已设置
  setTimeout(() => {
        // 如果有保存的选区，恢复它
        if (savedSelection) {
          restoreSelection(savedSelection);
        }
        // 添加关键词到光标位置
        addKeywordToPrompt(colorId);
      }, 10);
    } else {
      addKeywordToPrompt(colorId);
    }
  }
}

// 创建任务函数
async function createTask() {
  if (isGenerating.value) return;
  
  // 获取最终的提示词
  let prompt = finalPrompt.value;
  if (!prompt.trim()) {
    // 如果提示词为空，给出提示
    alert('请输入描述词');
    return;
  }
  
  // 状态更新
  isGenerating.value = true;
  
  try {
    // 首先获取所有关键词，并按index排序
    const sortedKeywords = Object.entries(keywords)
      .map(([colorId, keyword]) => ({ colorId, ...keyword }))
      .sort((a, b) => a.index - b.index);
    
    // 创建k值到数组下标的映射
    const kToIndexMap = new Map();
    sortedKeywords.forEach((keyword, index) => {
      kToIndexMap.set(`k${keyword.index}`, index);
    });
    
    // 替换提示词中的 {k?} 为 {0}, {1}, ...
    prompt = prompt.replace(/\{k(\d+)\}/g, (match, kNumber) => {
      const index = kToIndexMap.get(`k${kNumber}`);
      return (index !== undefined) ? `{${index}}` : match;
    });
    
    console.log('处理后的提示词:', prompt);
    
    // 根据taskType构建不同的请求体
    let requestBody: any;
    
    if (isAI.value) {
      // AI 类型的请求
      requestBody = {
        taskType: 1,
        taskCategory: taskCategoryDict[selectedCategory.value] || "M",
        taskGenQty: PicsliderValue.value,
        taskPrompt: prompt,
        taskSwitchNum: Math.floor(switchNumsliderValue.value / 4), // 确保整除4
        imgSize: imgSize.value,
        // personName: selectedPerson.value
      };
    } else {
      // 普通类型的请求
      // 格式化关键词为insertPoints
      const insertPoints: Record<string, string> = {};
      
      // 使用排序后的关键词数组来创建insertPoints
      sortedKeywords.forEach((keyword, index) => {
        if (keyword.value.trim()) {
          insertPoints[`insert${index + 1}`] = keyword.value.replace(/,/g, '^');
        }
      });
      
      requestBody = {
        taskType: 0,
        taskCategory: taskCategoryDict[selectedCategory.value] || "M",
        taskGenQty: PicsliderValue.value,
        taskPrompt: prompt,
        imgSize: imgSize.value,
        insertPoints: Object.keys(insertPoints).length > 0 ? insertPoints : undefined,
        // personName: selectedPerson.value
      };
    }
    
    console.log('创建任务请求体:', requestBody);
    
    // 发送请求 - 使用正确的 endpoint
    const response = await axiosInstance.post('/mj/api/tasks', requestBody);
    console.log('创建任务成功:', response);
    
    // 处理响应
    alert('任务创建成功!');
    
  } catch (error: any) {
    console.error('创建任务失败:', error);
    alert(`创建任务失败: ${error.message || '未知错误'}`);
  } finally {
    isGenerating.value = false;
  }
}
</script>

<template>
  <div class="upload-container">
    <!-- <h2 class="page-title">图生图</h2> -->
    
    <div class="upload-section">
      <div class="prompt-area">
        <div class="prompt-header">
          <h3 class="prompt-title">描述词</h3>
          <div class="keyword-dots">
            <span 
              v-for="(keyword, id) in keywords" 
              :key="id"
              class="keyword-dot"
              :style="{ backgroundColor: keyword.color }"
              @click.stop.prevent="addKeywordWithColor(id)"
              :title="`k${keyword.index} - ${keyword.value || '点击添加到描述词'}`"
            ></span>
            <button @click.stop.prevent="addKeywordTag" class="add-keyword-btn" title="添加关键词标签">
              +
            </button>
            <!-- 添加调试按钮，用于手动重新扫描关键词（在生产环境可移除） -->
            <!-- <button 
              @click.stop.prevent="rescanKeywords" 
              class="debug-btn" 
              title="手动重新扫描关键词" 
              style="color: #666; font-size: 0.75rem; padding: 0.25rem; margin-left: 0.5rem;">
              🔍
            </button> -->
          </div>
        </div>
          
        <div class="prompt-input-container">
          <div 
            contenteditable="true"
            @input="handlePromptInput"
            @mousedown.stop
            @mouseup.stop
            @click="(e) => { if (e.target) { (e.target as HTMLElement).focus(); saveCurrentSelection(e.target as HTMLElement); } }"
            @focus="(e) => { if (e.target) { (e.target as HTMLElement).focus(); saveCurrentSelection(e.target as HTMLElement); } }"
            @blur="(e) => { if (e.target) saveCurrentSelection(e.target as HTMLElement); }"
            @keyup="(e) => { if (e.target) saveCurrentSelection(e.target as HTMLElement); }"
            class="prompt-input"
            data-placeholder="输入描述词，点击上方彩色圆点或+号添加关键词..."
          ></div>
          
          <div 
            contenteditable="true"
            class="prompt-preview"
            @input="handlePreviewInput"
          ></div>
          <div class="controls-container">
            <label class="checkbox-control">
              <input type="checkbox" v-model="isAI">
              <span class="checkmark"></span>
              isAI
            </label>
            <div class="slider-container">
              <input 
                type="range" 
                min="0" 
                max="100" 
                v-model="PicsliderValue"
                class="optimization-slider"
              >
              <span class="slider-value">{{ PicsliderValue }}</span>
            </div>
            <transition name="fade">
              <label class="select-control" v-if="isAI">
                <span class="select-label">switchNum:</span>
                <select v-model="switchNumsliderValue" class="optimization-select">
                  <option v-for="num in [4, 8, 12, 16, 20, 24, 28, 32]" :key="num" :value="num">{{ num }}</option>
                </select>
              </label>
            </transition>
            <label class="select-control">
              <span class="select-label">尺寸:</span>
              <select v-model="imgSize" class="optimization-select">
                <option v-for="size in imgSizeOptions" :key="size" :value="size">{{ size }}</option>
              </select>
            </label>
            <label class="select-control">
              <span class="select-label">类别:</span>
              <select v-model="selectedCategory" class="optimization-select">
                <option v-for="(category, index) in Object.keys(taskCategoryDict)" :key="index" :value="category">
                  {{ category }}
                </option>
              </select>
            </label>
            <label class="select-control">
              <span class="select-label">处理人:</span>
              <select v-model="selectedPerson" class="optimization-select">
                <option v-for="(person, index) in processPerson" :key="index" :value="person">
                  {{ person }}
                </option>
              </select>
            </label>
          </div>
           <div class="generate-section">
      <button 
        @click="createTask" 
        class="btn btn-primary generate-btn"
        :disabled="isGenerating"
      >
        {{ isGenerating ? '创建中...' : '开始创建' }}
      </button>
    </div>
        </div>
      </div>
      
      <div class="keywords-area">
        <h3 class="keywords-title" style="margin-top: 0; margin-bottom: 1rem;">关键词</h3>
        <div class="keywords-container">
          <div 
            v-for="(keyword, id) in Object.entries(keywords).sort((a, b) => a[1].index - b[1].index)" 
            :key="id"
            class="keyword-input-group"
          >
            <div 
              class="keyword-label"
              :style="{ backgroundColor: keyword[1].color }"
              @click="addKeywordToPrompt(keyword[0])"
            >
              <span class="keyword-marker">k{{ keyword[1].index }}</span>
            </div>
            <div class="keyword-input-container">
            <input 
              v-model="keywords[keyword[0]].value"
              type="text"
              class="keyword-input"
                :class="`keyword-input-k${keyword[1].index}`"
              :placeholder="'输入关键词'"
                @input="(e) => handleKeywordInput(e, keyword[0])"
                :data-keyword-id="keyword[0]"
                :data-keyword-index="keyword[1].index"
              />
              <div 
                class="keyword-translation" 
                :class="`keyword-translation-k${keyword[1].index}`"
                contenteditable="true" 
                :data-keyword-id="keyword[0]"
                :data-keyword-index="keyword[1].index"
                placeholder="翻译内容"
              ></div>
            </div>
            <button 
              @click="deleteKeyword(keyword[0])" 
              class="keyword-delete-btn"
              title="删除关键词"
            >
              ✕
            </button>
          </div>
        </div>
      </div>
    </div>
    
   
  </div>
</template>

<style scoped>
.generate-section {
  display: flex;
  justify-content: center;
  align-items: center;
  /* margin-top: 1.5rem; */
  position: relative;
  clear: both;
  padding-top: 1rem;
  /* margin-bottom: 1.5rem; */
  z-index: 5;
}

.generate-btn {
  width: 100%;
  max-width: 300px;
  padding: 0.75rem 1.5rem;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 auto;
  display: block;
  z-index: 10;
  background-color: #4361ee;
  color: white;
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

.generate-btn:hover {
  background-color: #3a56d4;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}

.generate-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.upload-container {
  padding: 1rem 0;
}

.keywords-area {
  background-color: var(--bg-secondary);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
  padding: 0.5rem;
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 350px;
  overflow: hidden;
}

.upload-section {
  display: grid;
  grid-template-columns: 4fr 2.5fr;
  gap: 1.5rem;
  margin-bottom: 1rem;
  max-height: 350px;
  transition: all 0.3s ease;
}

.keywords-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1rem;
  max-height: calc(100% - 3rem);
  overflow-y: auto;
  padding-right: 0.5rem;
  flex: 1;
  scrollbar-width: thin;
}

.keywords-container::-webkit-scrollbar {
  width: 6px;
}

.keywords-container::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 3px;
}

.keywords-container::-webkit-scrollbar-thumb {
  background-color: var(--border-color);
  border-radius: 3px;
}

.controls-dropdown-group {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
  margin-top: 0.5rem;
  justify-content: flex-start;
}

.page-title {
  margin-bottom: 2rem;
  color: var(--text-primary);
  font-size: 1.75rem;
  text-align: center;
}

.prompt-area {
  background-color: var(--bg-secondary);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
  padding: 1rem;
  display: flex;
  flex-direction: column;
  min-height: 300px;
  overflow: hidden;
}

.prompt-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}

.prompt-title {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.25rem;
}

.keyword-dots {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.keyword-dot {
  width: 1rem;
  height: 1rem;
  border-radius: 50%;
  cursor: pointer;
  transition: transform var(--transition-fast);
  display: block; /* 确保小圆点显示 */
}

.keyword-dot:hover {
  transform: scale(1.2);
}

.add-keyword-btn {
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 50%;
  background-color: var(--bg-tertiary);
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  cursor: pointer;
  border: none;
  padding: 0;
}

.prompt-input-container {
  position: relative;
  /* margin-bottom: 1rem; */
  flex: 1;
}

.prompt-input {
  width: 100%;
  max-height: 200px;
  padding: 0.75rem 1rem;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-sm);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  min-height: 100px;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5;
  overflow-y: hidden;

  /* user-select: text !important; 
  -webkit-user-select: text !important;
  -moz-user-select: text !important; 
  -ms-user-select: text !important; 
  cursor: text !important; 
  white-space: pre-wrap; 
  word-break: break-word; 
  position: relative; 
  z-index: 1;  */
}

.prompt-input[contenteditable=true]:empty:before {
  content: attr(data-placeholder);
  color: var(--text-tertiary);
  pointer-events: none;
}

.prompt-input::selection {
  background-color: rgba(var(--primary-color-rgb), 0.2);
}

.prompt-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.prompt-preview {
  max-height: 180px;
  margin-top: 0.5rem;
  padding: 0.75rem;
  overflow-y: hidden;
  border-radius: var(--border-radius-sm);
  background-color: var(--bg-tertiary);
  /* min-height: 2rem; */
  line-height: 1.5;
}

.controls-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 1rem 0;
  padding: 0.5rem 1rem;
  background-color: var(--bg-tertiary);
  border-radius: var(--border-radius-sm);
  flex-wrap: wrap;
  gap: 0.5rem;
}

.checkbox-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.checkbox-control input {
  opacity: 0;
  position: absolute;
}

.checkmark {
  display: inline-block;
  width: 1.1em;
  height: 1.1em;
  border: 2px solid var(--primary-color);
  border-radius: 4px;
  position: relative;
}

.checkbox-control input:checked ~ .checkmark::after {
  content: '✓';
  position: absolute;
  left: 50%;
  top: 45%;
  transform: translate(-50%, -50%);
  color: var(--primary-color);
}

.slider-container {
  display: flex;
  align-items: center;
  gap: 1rem;
  width: 500px;
}

.optimization-slider {
  flex: 1;
  height: 4px;
  margin-right: 5px;
  margin-left: 5px;
  background: var(--border-color);
  border-radius: 2px;
  outline: none;
  -webkit-appearance: none;
}

.optimization-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  background: var(--primary-color);
  border-radius: 50%;
  cursor: pointer;
}

.slider-value {
  min-width: 50px;
  text-align: center;
  color: var(--text-secondary);
}

.isAiGenerated {
  margin-top: 0.5rem;
  padding: 0.75rem;
  border-radius: var(--border-radius-sm);
  background-color: var(--bg-tertiary);
  min-height: 2rem;
  line-height: 1.5;
}

.keyword-tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: var(--border-radius-sm);
  color: white;
  font-weight: 500;
  margin: 0 0.25rem;
  user-select: all !important; /* 确保标签作为一个整体被选择 */
  -webkit-user-select: all !important; /* Safari 支持 */
  -moz-user-select: all !important; /* Firefox 支持 */
  -ms-user-select: all !important; /* IE/Edge 支持 */
  cursor: default; /* 显示默认光标 */
  white-space: nowrap; /* 防止标签内容换行 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  position: relative; /* 为可能的悬停效果做准备 */
  transition: transform 0.1s ease, box-shadow 0.1s ease; /* 平滑过渡效果 */
  pointer-events: none; /* 防止标签捕获鼠标事件，允许文本选择穿透 */
}

.keyword-tag:hover {
  transform: translateY(-1px); /* 悬停时轻微上移 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15); /* 悬停时增强阴影 */
}

.keyword-input-group {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  width: 100%;
  margin-bottom: 1rem;
}

.keyword-label {
  padding: 0.25rem 0.5rem;
  border-radius: var(--border-radius-sm);
  color: white;
  font-weight: 500;
  font-size: 0.875rem;
  white-space: nowrap;
}

.keyword-input {
  flex: 1;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-sm);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 0.875rem;
  display: block;
  width: 100%;
  box-sizing: border-box;
}

.keyword-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.keyword-delete-btn {
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 50%;
  background-color: var(--bg-tertiary);
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  cursor: pointer;
  border: none;
  padding: 0;
  transition: background-color var(--transition-fast), color var(--transition-fast);
  align-self: flex-start;
}

.keyword-delete-btn:hover {
  background-color: #ff6b6b;
  color: white;
}

.loading-dots {
  display: inline-block;
  position: relative;
  width: 1rem;
  height: 1rem;
}

.loading-dots::after {
  content: '...';
  animation: loading-dots 1.5s infinite;
}

@keyframes loading-dots {
  0% { content: '.'; }
  33% { content: '..'; }
  66% { content: '...'; }
}

.generated-images-section {
  margin-top: 3rem;
}

.section-title {
  margin-bottom: 1.5rem;
  color: var(--text-primary);
  font-size: 1.5rem;
  text-align: center;
}

.generated-images-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
}

.generated-image-card {
  background-color: var(--bg-secondary);
  border-radius: var(--border-radius-md);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  cursor: pointer;
  transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}

.generated-image-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-md);
}

.generated-image {
  width: 100%;
  aspect-ratio: 1 / 1;
  object-fit: cover;
}

.image-prompt {
  padding: 1rem;
  font-size: 0.875rem;
  color: var(--text-secondary);
  background-color: var(--bg-secondary);
  border-top: 1px solid var(--border-light);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式设计 - 桌面端适配 */
@media (max-width: 768px) {
  .upload-section {
    grid-template-columns: 1fr;
  }
  
  .generated-images-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .controls-container {
    flex-direction: flex;
    align-items: flex-start;
  }
  
  .controls-dropdown-group {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 480px) {
  .generated-images-grid {
    grid-template-columns: 1fr;
  }
}

@media (min-width: 769px) {
  .upload-container {
    padding: 2rem 0;
  }
  
  .page-title {
    font-size: 2rem;
    margin-bottom: 3rem;
  }
  
  .upload-section {
    grid-template-columns: 5fr 3fr;
    gap: 2rem;
  }
  
  .prompt-input {
    min-height: 100px;
  }
  
  .keywords-container {
    grid-template-columns: 1fr;
  }
}

.select-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background-color: var(--bg-primary);
  border-radius: var(--border-radius-sm);
  padding: 0.3rem 0.5rem;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color);
}

.select-label {
  font-size: 0.875rem;
  color: var(--text-secondary);
  white-space: nowrap;
}

.optimization-select {
  padding: 0.3rem 0.5rem;
  border-radius: var(--border-radius-sm);
  border: 1px solid var(--border-color);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  outline: none;
  font-size: 0.875rem;
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 0.5rem center;
  background-size: 1rem;
  padding-right: 1.5rem;
}

.optimization-select:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.2);
}

/* 新增关键词翻译框样式 */
.keyword-input-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 4px;
}

.keyword-translation {
  min-height: 30px;
  padding: 4px 8px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  background-color: rgba(245, 245, 245, 0.5);
  font-size: 0.9em;
  color: #333;
  transition: all 0.3s ease;
  overflow-wrap: break-word;
  word-break: break-all;
}

.keyword-translation:focus {
  outline: none;
  border-color: #4CAF50;
  background-color: rgba(236, 255, 236, 0.7);
  box-shadow: 0 0 3px rgba(76, 175, 80, 0.5);
}

.keyword-translation:empty:before {
  content: "翻译将在此显示";
  color: #aaa;
  font-style: italic;
}

.keyword-translation.loading:after {
  content: "正在翻译...";
  color: #666;
  font-style: italic;
  animation: blink 1s infinite;
}

@keyframes blink {
  0% { opacity: 0.3; }
  50% { opacity: 1; }
  100% { opacity: 0.3; }
}

/* 其他已有样式 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity: 0;
}

.select-control {
  flex: 1;
  /* min-width: 100px; */
}
</style>